package org.aplikator.client.shared.rpc.marshaller;

import org.aplikator.client.shared.data.Record;
import org.aplikator.client.shared.data.SearchResult;
import org.jboss.errai.marshalling.client.api.MarshallingSession;
import org.jboss.errai.marshalling.client.api.annotations.ClientMarshaller;
import org.jboss.errai.marshalling.client.api.annotations.ServerMarshaller;
import org.jboss.errai.marshalling.client.api.json.EJObject;
import org.jboss.errai.marshalling.client.api.json.EJValue;
import org.jboss.errai.marshalling.client.marshallers.AbstractNullableMarshaller;

import java.util.List;

@ClientMarshaller(SearchResult.class)
@ServerMarshaller(SearchResult.class)
@SuppressWarnings("unchecked")
public class SearchResultMarshaller extends AbstractNullableMarshaller<SearchResult> {

	/*@Override
	public Class<SearchResult> getTypeHandled() {
		return SearchResult.class;
	}*/

	@Override
	public SearchResult[] getEmptyArray() {
		return new SearchResult[0];
	}

	@Override
	public SearchResult doNotNullDemarshall(EJValue o, MarshallingSession ctx) {
		if (o.isObject() != null) {
			SearchResult sresult = new SearchResult();
			EJObject ejObject = o.isObject();
			sresult.setCount( new Long(ejObject.get("count").isNumber().intValue()));
			List l = DemarshallingUtils.listUnMarshall(ejObject.get("records"), ctx, Record.class.getName());
			sresult.setRecords(l);
			return sresult;
		} else  return null;
	}

	@Override
	public String doNotNullMarshall(SearchResult o, MarshallingSession ctx) {
		StringBuilder builder = new StringBuilder().append('{');
		MarshallingUtils.number("count", o.getCount(),builder).append(',');
		MarshallingUtils.key("records", builder).append(':');
		MarshallingUtils.listMarshall(builder, o.getRecords(), ctx, Record.class.getName());
		builder.append('}');
		return builder.toString();
	}
}
